package com.bstek.weixin.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 微信接口 调用基础
 * @author snail
 * @date 2019年1月2日
 */
public class WeixinCommUtil {

	private static final Log log=LogFactory.getLog(WeixinCommUtil.class);
	
	/**
	 * 通过 url获取微信 信息
	 * @author snail
	 * @date 2018年12月12日
	 * @param weixinUrl,method
	 * @return
	 * @throws IOException 
	 */
	public static JSONObject getWeixInfo(String weixinUrl,String method) throws IOException {
		BufferedReader br=null;
		if(weixinUrl!=null) {
			try {
				URL weixurl=new URL(weixinUrl);
				HttpsURLConnection httpClient=(HttpsURLConnection) weixurl.openConnection();
				httpClient.setRequestMethod(method);
				httpClient.connect();
				br=new BufferedReader(
						new InputStreamReader(httpClient.getInputStream(), "UTF-8"));
				StringBuilder result=new StringBuilder();
				String line=null;
				while((line=br.readLine())!=null) {
					result.append(line);
				}
				httpClient.disconnect();//销毁连接
				if(result!=null&&result.length()>0) {
					JSONObject json=JSONObject.parseObject(result.toString());
					return json;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.info("调用接口 webservice异常"+e);
				return null;
			}finally {
				if(br!=null) {
					br.close();
				}
			}
		}
		return null;
	}
	
	
	/**
	 * 通过 企业ID 获取微信 操作凭证 access_token(操作相同的东西 这个access_token最好缓存起来 如：通讯录
	 *   原因：① 微信有限制时间内不能重复调用次数 ②性能优化的角度)
	 * @author snail
	 * @date 2018年12月10日
	 * @param corpId
	 * @param corpSecret
	 * @return
	 * @throws IOException 
	 */
	public static String getWeixinToken(String corpId,String corpSecret) throws IOException {
		if(corpId!=null&&corpSecret!=null) {
			//判断缓存中是否存在该 token
			String cachetoken=(String) CacheUtil.getCacheParams(corpId+corpSecret);
			if(StringUtils.hasText(cachetoken)) {
				return cachetoken;
			}
			String getTokenURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +
					corpId + "&corpsecret=" + corpSecret;
			BufferedReader br=null;
			try {
				URL weixurl=new URL(getTokenURL);
				HttpsURLConnection httpClient=(HttpsURLConnection) weixurl.openConnection();
				httpClient.setRequestMethod("GET");
				httpClient.connect();
				br=new BufferedReader(
						new InputStreamReader(httpClient.getInputStream(), "UTF-8"));
				StringBuilder result=new StringBuilder();
				String line=null;
				while((line=br.readLine())!=null) {
					result.append(line);
				}
				//获取token
				httpClient.disconnect();//销毁连接
				if(result!=null&&result.length()>0) {
					JSONObject json=JSONObject.parseObject(result.toString());
					Integer errcode=(Integer)json.get("errcode");
					if(errcode!=null&&errcode==0) {
						String token=(String)json.get("access_token");
						CacheUtil.setCacheParams(corpId+corpSecret, token);//token放到缓存中
						return token;
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.info("调用接口 webservice异常"+e);
				return null;
			}finally {
				if(br!=null) {
					br.close();
				}
			}
			
		}
		return null;
	}
	
	
	/**
	 *  调用接口连接返回json参数
	 * @author snail
	 * @date 2018年12月12日
	 * @param Url 
	 * @param method get和set方法
	 * @param content 内容
	 * @return
	 * @throws IOException 
	 */
	public static JSONObject operatorWeixin(String Url,String method,String content) throws IOException {
		if(Url!=null&&method!=null&&content!=null) {
			OutputStream os=null;
			BufferedReader br=null;
			try {
				URL weixurl=new URL(Url);
				HttpsURLConnection httpClient=(HttpsURLConnection) weixurl.openConnection();
				httpClient.setDoOutput(true);
				httpClient.setDoInput(true);
				httpClient.setUseCaches(false);
				httpClient.setRequestMethod(method);
				//发送内容 获取输出流
				os=httpClient.getOutputStream();
				os.write(content.getBytes("UTF-8"));
				os.close();
				//
				httpClient.connect();
				br=new BufferedReader(
						new InputStreamReader(httpClient.getInputStream(), "UTF-8"));
				StringBuilder result=new StringBuilder();
				String line=null;
				while((line=br.readLine())!=null) {
					result.append(line);
				}
				httpClient.disconnect();//销毁连接
				//获取token
				if(result!=null&&result.length()>0) {
					JSONObject json=JSONObject.parseObject(result.toString());
					return json;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.info("调用接口 webservice异常"+e);
				return null;
			}finally {
				if(br!=null) {
					br.close();
				}
				if(os!=null) {
					os.close();
				}
			}
		}
		return null;
	}
	
}
